package com.vtmer.controller;

import com.vtmer.entity.User;
import com.vtmer.result.ResultVo;
import com.vtmer.result.impl.ResultCode;
import com.vtmer.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author Colin
 */
@RestController
public class LoginController {

    @Resource
    UserService userService;

    @GetMapping("/login/{uid}/{password}")
    public ResultVo<User> login(@PathVariable int uid,
                                @PathVariable String password) {
        Optional<User> optionalUser = Optional.ofNullable(getUserInfoByIdAndPassword(uid, password));
        return optionalUser.map(ResultVo::new).orElseGet(() -> new ResultVo<>(ResultCode.LOGIN_ERROR));
    }

    /**
     * 获取用户信息
     *
     * @param uid      用户id
     * @param password 密码
     * @return 返回User对象
     */
    private User getUserInfoByIdAndPassword(int uid, String password) {
        return userService.getUserByIdAndPassword(uid, password);
    }

    @GetMapping("/administrators/{uid}/{password}")
    public ResultVo<User> admin(@PathVariable int uid,
                                @PathVariable String password) {
        Optional<User> optionalUser = Optional.ofNullable(getUserInfoByIdAndPassword(uid, password));
        return optionalUser.filter(u -> u.getUserRole() == 1).map(ResultVo::new).orElseGet(() -> new ResultVo<>(ResultCode.LOGIN_ERROR));
    }

}
